package ServerStuff;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import DataStorageClasses.Client;
import Database.DatabaseConnector;


@WebServlet("/listClientsServlet")
public class listClientsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DatabaseConnector dbConnect = new DatabaseConnector();
		HttpServletRequest req = (HttpServletRequest) request;
		//HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		String busName = (String) session.getAttribute("username");
		
		ArrayList<Client> clients = dbConnect.getClients(null, null, null, null, null, 
														null, null, null, null, null, busName);
		
		JSONObject result = new JSONObject();
		
		JSONArray jArray = new JSONArray();
		
		try {
			for(Client client : clients) {
				String s = String.valueOf(client.getClientId());
				String name = s + " " + client.getFirstName() + " " + client.getLastName();
				//System.out.println(name);
				jArray.put(name);
			}
		
			result.put("clients", jArray);
			
			response.getWriter().print(result.toString());
			response.setStatus(HttpURLConnection.HTTP_ACCEPTED);
		}
		catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
		}
	}

}
